//
//  RecordTailViewController.m
//  iStore
//
//  Created by MacDev on 15/4/24.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//


#import "RecordTailViewController.h"
#import "LDProgressView.h"
#import "SendADViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "VoiceConverter.h"

#define  kMaxLength  30


@interface RecordTailViewController () <AVAudioRecorderDelegate ,UIGestureRecognizerDelegate,AVAudioPlayerDelegate,UIScrollViewDelegate,UITextFieldDelegate>
{
    LDProgressView *_progressView;
    //录音的系统类
    AVAudioRecorder *_recorder;
    //播放音频
    AVAudioPlayer *_player;
    
    BOOL _click;
    
    // 手势
    UILongPressGestureRecognizer *_longPGR;
    
    // 定时器
    //   NSTimer * _timer;
    
    // 文件路径
    NSURL *_url;
    //福利类型
    NSString *_welfare;
    
}


@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation RecordTailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"制作尾标宣传内容";
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNextView)];
    _imageView.userInteractionEnabled = YES;
    _scrollView.delegate = self;
    
    
    [self createProgressView];
    [self createLongGesture];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:kAudioFilePath error:nil];
    self.navigationItem.leftBarButtonItem.title = @"返回";
}
// 创建进度条
- (void)createProgressView
{
    _progressView = [[LDProgressView alloc] initWithFrame:CGRectMake(20, 20,[UIScreen mainScreen].bounds.size.width-40, 20)];
    _progressView.color = [UIColor colorWithRed:0.02f green:0.74f blue:0.03f alpha:1.00f];
    
    _progressView.flat = @YES;
    _progressView.animate = @YES;
    _progressView.borderRadius = @5;
    _progressView.progress = 0;
    [_myView addSubview:_progressView];
}

- (void)gotoNextView
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:kAudioFilePath] && _textFile.text.length == 0) {
        alert(@"请制作广告内容");
        return;
    }
    SendADViewController * sVC = [[SendADViewController alloc]init];
    sVC.type = @"1";
    sVC.radioText = _textFile.text;
    
    [[NSUserDefaults standardUserDefaults]setObject:_welfare forKey:KwealfareType];
    [self.navigationController pushViewController:sVC animated:YES];
}
- (void)translate
{
    [VoiceConverter wavToAmr:kAudioFilePath amrSavePath:kAudioAmrFilePath];
}
// 创建录音方法
- (void)createRecord
{
    _url = [NSURL fileURLWithPath:kAudioFilePath];
    
    
    if (_recorder == nil) {
        
        //真机运行在ios7以后加上如下代码就ok
        AVAudioSession *session = [AVAudioSession sharedInstance];
        
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session == nil) {
            //      NSLog(@"%@",sessionError);
        }
        else
        {
            [session setActive:YES error:nil];
        }
        
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 8000.0],AVSampleRateKey, //采样率
                              [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                              [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,//采样位数 默认 16
                              [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,//通道的数目
                              //                                   [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,//大端还是小端 是内存的组织方式
                              //                                   [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,//采样信号是整数还是浮点数
                              //                                   [NSNumber numberWithInt: AVAudioQualityMedium],AVEncoderAudioQualityKey,//音频编码质量
                              nil];
        
        
        //创建AVAudioRecorder对象
        
        NSError *error = nil;
        _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:kAudioFilePath] settings:dict error:&error];
        
        //设置代理
        _recorder.delegate = self;
        if (error) {
            NSLog(@"record error = %@",error);
        }
        //准备录音
        [_recorder prepareToRecord];
        
        
        
    }
    
}

// 创建手势
- (void)createLongGesture
{
    _longPGR = [[UILongPressGestureRecognizer alloc]init];
    [_longPGR addTarget:self action:@selector(longPressGes:)];
    [_imageView addGestureRecognizer:_longPGR];
    
}
// 创建播放
- (void)createAudioPlayer
{
    if (_player == nil) {
        NSError * error = nil;
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:kAudioFilePath] error:&error];
        _player.delegate = self;
        if (error) {
            
        }
    }
}

#pragma mark -- 手势代理----

- (void)longPressGes:(UILongPressGestureRecognizer *)ges
{
    [self createRecord];
    if (ges.state == UIGestureRecognizerStateBegan) {
        
        
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        
        //        [_recorder record];
        
        [_recorder recordForDuration:8.0f];
        
        [_imageView setImage:[UIImage imageNamed:@"1112"]];
        
        [_progressView setProgress:1 withTime:8];
        
        [_audition setTitle:@"试听录音" forState:UIControlStateNormal];
        
        
        
    }
    else if (ges.state == UIGestureRecognizerStateEnded)
    {
        
        [_recorder stop];
        
        [_imageView setImage:[UIImage imageNamed:@"record.png"]];
        
        [_progressView stopTime];
        
        //       NSLog(@"%f",myTimer);
    }
}



- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    _audition.titleLabel.text = @"试听录音";
    [_progressView stopTime];
    _click = YES;
}


- (IBAction)recordButton:(UIButton *)sender {
    if (sender.tag == 100) {
        [sender setEnabled:YES];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:kAudioFilePath error:nil];
        [_progressView setProgress:0 withTime:0];
        
    }if (sender.tag == 102) {
        
        //初始化播放器的时候如下设置
        UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
        AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                                sizeof(sessionCategory),
                                &sessionCategory);
        
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                                 sizeof (audioRouteOverride),
                                 &audioRouteOverride);
        
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        [session setActive:YES error:nil];
        
        if (_player.isPlaying) {
            [sender setTitle:@"试听录音" forState:UIControlStateNormal];
            [_player stop];
            [_progressView stopTime];
            _player = nil;
        }else {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if (![fileManager fileExistsAtPath:kAudioFilePath]) {
                alert(@"你播放的录音不存在");
                [sender setTitle:@"试听录音" forState:UIControlStateNormal];
                return;
            }
            _player = [[AVAudioPlayer alloc] initWithContentsOfURL:_url error:nil];
            _player.delegate = self;
            [sender setTitle:@"停止播放" forState:UIControlStateNormal];
            [_player prepareToPlay];
            [_player play];
            [_progressView setProgress:1 withTime:_player.duration];
        }
    }
}

//广告福利选择
- (void)radioButton:(NSInteger )integer
{
    _welfare = [NSString stringWithFormat:@"%d",(int)(integer % 10)];
    for (int i=200; i<204; i++) {
        if (i != integer) {
            UIButton *subBtn = (UIButton *)[self.view viewWithTag:i];
            [subBtn setImage:[UIImage imageNamed:@"Check-box_1"] forState:UIControlStateNormal];
            subBtn.selected = NO;
        }
    }
}
- (IBAction)chooseButton:(UIButton *)sender
{
    if (sender.selected == YES) {
        sender.selected = NO;
        [sender setImage:[UIImage imageNamed:@"Check-box_1"] forState:UIControlStateNormal];
    }
    else {
        sender.selected = YES;
        [sender setImage:[UIImage imageNamed:@"Check-box"] forState:UIControlStateNormal];
    }
    [self radioButton:sender.tag];
    
}
- (IBAction)expandButton:(UIButton *)sender {
    [self chooseButton:(UIButton*)[self.view viewWithTag:200+sender.tag%10]];
}
//退出键盘
- (void)touchScrollView:(UITapGestureRecognizer*)recognizer
{
    [_textFile resignFirstResponder];
    [_scrollView removeGestureRecognizer:recognizer];
}
- (IBAction)textFileBegin:(UITextField *)sender {
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView:)];
    [recognizer setNumberOfTapsRequired:1];
    [recognizer setNumberOfTouchesRequired:1];
    [_scrollView addGestureRecognizer:recognizer];
}
#pragma mark --输入框字数控制--
-(IBAction)limitLength:(UITextField *)sender
{
    bool isChinese;//判断当前输入法是否是中文
    if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @"en-US"]) {
        isChinese = false;
    }
    else
    {
        isChinese = true;
    }
    
    if(sender == self.textFile) {
        // 8位
        NSString *str = [[self.textFile text] stringByReplacingOccurrencesOfString:@"?" withString:@""];
        if (isChinese) { //中文输入法下
            UITextRange *selectedRange = [self.textFile markedTextRange];
            //获取高亮部分
            UITextPosition *position = [self.textFile positionFromPosition:selectedRange.start offset:0];
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                
                _label.text = [NSString stringWithFormat:@"%lu/30字",(unsigned long)str.length];
                if ( str.length > kMaxLength) {
                    
                    
                    _label.text = [NSString stringWithFormat:@"%d/30字",kMaxLength];
                    NSString *strNew = [NSString stringWithString:str];
                    [self.textFile setText:[strNew substringToIndex:kMaxLength]];
                }
            }
            else
            {
                //                NSLog(@"输入的英文还没有转化为汉字的状态");
                
            }
        }else{
            //           NSLog(@"str=%@; 本次长度=%lu",str,(unsigned long)[str length]);
            _label.text = [NSString stringWithFormat:@"%lu/30字",(unsigned long)str.length];
            if ([str length] > kMaxLength) {
                _label.text = [NSString stringWithFormat:@"%d/30字",kMaxLength];
                NSString *strNew = [NSString stringWithString:str];
                [self.textFile setText:[strNew substringToIndex:kMaxLength]];
            }
        }
    }
}

- (IBAction)EditingChanged:(UITextField *)sender {
    [self.textFile addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];
}


@end
